package rs.ac.uns.ftn.informatika.mbs2.e11031.etaksi.servlet;

import java.io.IOException;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.validator.GenericValidator;
import org.apache.log4j.Logger;

import rs.ac.uns.ftn.informatika.mbs2.e11031.etaksi.dao.KorisnikDao;
import rs.ac.uns.ftn.informatika.mbs2.e11031.etaksi.entitet.Administrator;
import rs.ac.uns.ftn.informatika.mbs2.e11031.etaksi.entitet.Korisnik;
import rs.ac.uns.ftn.informatika.mbs2.e11031.etaksi.entitet.Vozac;

@SuppressWarnings("serial")
public class PrijavaKontroler extends HttpServlet {

	@EJB
	private KorisnikDao cKorisnikDao;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		String korisnickoIme = req.getParameter("korisnickoIme");
		String lozinka = req.getParameter("lozinka");

		// ako je su prazna polja, vrati se na stranu za prijavu
		if (GenericValidator.isBlankOrNull(korisnickoIme)
				|| GenericValidator.isBlankOrNull(lozinka)) {
			resp.sendRedirect(resp.encodeRedirectURL("./jsp/prijava.jsp"));
		} else {

			Korisnik korisnik = cKorisnikDao.prijavi(korisnickoIme, lozinka);

			if (korisnik != null) {
				req.getSession().setAttribute("korisnik", korisnik);
				Logger.getRootLogger().trace(korisnickoIme);
				if (korisnik instanceof Administrator)
					getServletContext().getRequestDispatcher(
							"/PrikazVoznjiKontroler").forward(req, resp);
				else if (korisnik instanceof Vozac)
					getServletContext().getRequestDispatcher(
							"/PrikazNezapocetihVoznjiKontroler").forward(req,
							resp);
				else
					getServletContext().getRequestDispatcher(
							"/jsp/zahtevanjeVoznje.jsp").forward(req, resp);
			} else
				resp.sendRedirect(resp.encodeRedirectURL("./jsp/prijava.jsp"));
		}
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doGet(req, resp);
	}

}
